#include <fstream>
#include <stdlib.h>
#include "headfiles.h"

using namespace std;

bool readInput(const char *file_name, 
               int add_array_size, 
               int * &array, 
               int &elem_num) {
    if (file_name == NULL ||
        array == NULL) {
        cout << "Invalide input, NULL!" << endl;
        return false;
    }

    fstream fs;
    fs.open(file_name, fstream::in);
    if (fs.is_open() == false) {
        cout << "File " << file_name << " open error!" << endl;
        return false;
    }

    string str;
    fs >> str;
    if (str.empty()) {
        cout << "Empty file" << endl;
        return false;
    }

    elem_num = atoi(str.c_str());
    if (elem_num <= 0) {
        cout << "Invalide array size " << elem_num << "!" << endl;
        return false;
    }

    int array_size = elem_num + add_array_size;
    array = new int[array_size];
    if (array == NULL) {
        cout << "Allocate array buffer error, NULL!" << endl;
        return false;
    }

    int array_loc = 0;
    while (fs >> str) {
        if (str.empty()) {
            break;
        }

        int val = atoi(str.c_str());
        array[array_loc] = val;
        ++array_loc;
    }

    if (array_loc != elem_num) {
        cout << "Num of elements is incorrect in file " << file_name << "!" << endl;
        return false;
    }

    return true;
}

bool printArray(int *array, int elem_num) {
    if (array == NULL ||
        elem_num <= 0) {
        cout << "Invalid argument!" << endl;
        return false;
    }

    int i;
    for (i = 0; i < elem_num; i++) {
        cout << array[i] << "\t";
    }
    cout << endl;

    return true;
}


bool rotateArray(int *array, int elem_num, int rotate_num) {
    if (array == NULL) {
        cout << "Invalid argument, NULL!" << endl;
        return false;
    }

    // In case rotate_num is larger than elem_num
    int r_num = rotate_num % elem_num;

    int *tmp_array = new int[r_num];
    if (tmp_array == NULL) {
        cout << "Allocate tmp_array error, NULL!" << endl;
        return false;
    }

    int i;
    for (i = 0; i < r_num; i++) {
        tmp_array[i] = array[i];
    }

    for (; i < elem_num; i++) {
        array[i - r_num] = array[i];
    }

    for (i = 0; i < r_num; i++) {
        array[elem_num - r_num + i] = tmp_array[i];
    }

    delete tmp_array;

    return true;
}

